"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-
@Project : All_Designer
@File : ViewImage.py
@Author : RuanYaoHuang
@Time : 2023/3/12 22:08

"""
import numpy as np
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QImage, QPixmap
from arena_api.buffer import BufferFactory


class ViewThread(QThread):
    RawImage = pyqtSignal(np.ndarray)
    ReshapeImage = pyqtSignal(np.ndarray)
    def __init__(self, device, viewLabel, parent=None):
        super(ViewThread, self).__init__(parent)
        self.device = device
        self.viewLabel = viewLabel
        self.is_running = False
        node = self.device.nodemap.get_node(['PixelFormat'])
        self.pixelformat = node['PixelFormat'].value
        print(f'FormatPixel is :{self.pixelformat}')
    def run(self):
        self.is_running = True
        with self.device.start_stream():
            while self.is_running:
                """无限制获取，直到停止线程"""
                buffer = self.device.get_buffer()  # 获取缓冲区
                item = BufferFactory.copy(buffer)  # 复制缓冲区[并重新排队]，避免缓冲区用完
                self.read_img = np.array(item.data, dtype=np.uint8)  # 转换数据格式为Uint8
                # Aolp/Dolp_BayerRG8
                if self.pixelformat == 'PolarizedDolp_BayerRG8' or \
                        self.pixelformat == 'PolarizedAolp_BayerRG8':
                    self.Imgview_Data = self.read_img.reshape((1024, 1224))  # 还原图像分辨率
                # Aolp/Dolp_BayerRG12p
                elif self.pixelformat == 'PolarizedDolp_BayerRG12p' or \
                    self.pixelformat == 'PolarizedAolp_BayerRG12p':
                    img_bytes = np.unpackbits(self.read_img)  # 转换为2进制
                    img_bytes_reshape = img_bytes.reshape(-1, 12)  # 重置2进制矩阵shape
                    dot_array = np.dot(img_bytes_reshape, 2 ** np.arange(11, -1, -1))  # 将2进制矩阵还原成十进制
                    img_reshape = dot_array.reshape((1024, 1224))  # 还原图像分辨率
                    img_normalize = img_reshape / 4095.0  # 矩阵归一化
                    self.Imgview_Data = (img_normalize * 255.0).astype(np.uint8)  # 将矩阵转换为无符号8位
                # DolpAngle_BayerRG8
                elif self.pixelformat == 'PolarizedDolpAngle_BayerRG8':
                    img_bytes = np.unpackbits(self.read_img)  # 转换为2进制
                    img_bytes_reshape = img_bytes.reshape(-1, 16)  # 重置2进制矩阵shape
                    dot_array = np.dot(img_bytes_reshape, 2 ** np.arange(15, -1, -1))  # 将2进制矩阵还原成十进制
                    img_reshape = dot_array.reshape((1024, 1224))  # 还原图像分辨率
                    img_normalize = img_reshape / 65536.0  # 矩阵归一化
                    self.Imgview_Data = (img_normalize * 255.0).astype(np.uint8)  # 将矩阵转换为无符号8位
                # DolpAngle_BayerRG12p
                elif self.pixelformat == 'PolarizedDolpAngle_BayerRG12p':
                    img_bytes = np.unpackbits(self.read_img)  # 转换为2进制
                    img_bytes_reshape = img_bytes.reshape(-1, 24)  # 重置2进制矩阵shape
                    dot_array = np.dot(img_bytes_reshape, 2 ** np.arange(23, -1, -1))  # 将2进制矩阵还原成十进制
                    img_reshape = dot_array.reshape((1024, 1224))  # 还原图像分辨率
                    img_normalize = img_reshape / 16777216.0  # 矩阵归一化
                    self.Imgview_Data = (img_normalize * 255.0).astype(np.uint8)  # 将矩阵转换为无符号8位
                # 0-45-90-135/S0-S1-S2-S3/PolarizedDolpAngle_BayerRG16
                elif self.pixelformat == 'PolarizedAngles_0d_45d_90d_135d_BayerRG8' or \
                        self.pixelformat == 'PolarizedStokes_S0_S1_S2_S3_BayerRG8' or \
                        self.pixelformat == 'PolarizedDolpAngle_BayerRG16':
                    self.Imgview_Data = self.read_img.reshape((2048, 2448))  # 还原图像分辨率
                else:
                    pass
                # self.image_Data.emit(self.Imgview_Data)  # 发送线程中的数据给预览函数
                heigh, width = self.Imgview_Data.shape
                qimage = QImage(self.Imgview_Data, width, heigh, width, QImage.Format_Grayscale8)
                qpixmap = QPixmap.fromImage(qimage)
                scaled_pixmap = qpixmap.scaled(self.viewLabel.width(), self.viewLabel.height())
                self.viewLabel.setPixmap(scaled_pixmap)
                self.device.requeue_buffer(buffer)  # 对Buffer进行重新获取
                BufferFactory.destroy(item)  # 销毁Item中的数据，使得重新赋值
                self.RawImage.emit(self.read_img)   # 将raw原始值发给主线程
                self.ReshapeImage.emit(self.Imgview_Data)   # 将reshape后的raw矩阵发送给主线程

            self.device.stop_stream()   # 如果停止线程，则停止设备的传输流
    def stop(self):
        self.is_running = False
        print(f'ImageThread is Stop, and is_runing value is : {self.is_running}')
        self.wait()
